package com.baorant.springdemo1.config;

import com.baorant.springdemo1.domain.User;
import com.baorant.springdemo1.mapper.UserMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    /**
     * 安全过滤器链
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/"
                                , "/hello", "/user", "/login", "/insertUser", "/js/**"
                                , "/register", "/user/register").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        .loginPage("/login")          // 指定自定义登录页路径
                        .loginProcessingUrl("/user/login") // 指定登录接口地址（默认是 POST "/login"）
                        .defaultSuccessUrl("/user", true) // 登录成功后跳转
                        .failureUrl("/login")  // 登录失败跳转
                        .usernameParameter("name")   // 自定义用户名参数名（默认是 username）
                        .passwordParameter("password")   // 自定义密码参数名（默认是 password）
                )
                .logout(logout -> logout
                        .permitAll()
                ).csrf(csrf -> csrf.disable()); // 开发阶段可禁用 CSRF;

        return http.build();
    }

//    /**
//     *  用户详情服务,暂时内存demo
//     */
//    @Bean
//    public UserDetailsService userDetailsService() {
//        UserDetails user = User.withDefaultPasswordEncoder()
//                .username("user")
//                .password("password")
//                .roles("USER")
//                .build();
//
//        return new InMemoryUserDetailsManager(user);
//    }

    @Bean
    UserDetailsService userDetailsService(UserMapper userMapper) {
        return username -> {
            User user = userMapper.findByName(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户不存在");
            }
            return user;
        };
    }

    @Bean
    PasswordEncoder passwordEncoder() {
//        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return new BCryptPasswordEncoder();
    }
}
